package com.dengyafei.service.impl;

import com.dengyafei.bean.EnterpriseEntity;
import com.dengyafei.bean.GraduateEntity;
import com.dengyafei.bean.ResumeEntity;
import com.dengyafei.bean.ResumeEntityExample;
import com.dengyafei.constant.RecommendConstant;
import com.dengyafei.constant.RedisKeyConstant;
import com.dengyafei.domin.dto.ResumeAddDTO;
import com.dengyafei.domin.vo.*;
import com.dengyafei.helper.BeanHelper;
import com.dengyafei.mapper.DeliveryEntityMapper;
import com.dengyafei.mapper.EnterpriseEntityMapper;
import com.dengyafei.mapper.GraduateEntityMapper;
import com.dengyafei.mapper.ResumeEntityMapper;
import com.dengyafei.result.PageEntity;
import com.dengyafei.result.RedisShareEntity;
import com.dengyafei.result.RestApiResult;
import com.dengyafei.result.ResumeInfoEntity;
import com.dengyafei.service.ResumeService;
import com.dengyafei.utils.DateUtil;
import com.dengyafei.utils.JwtUtil;
import com.dengyafei.utils.RedisListUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.javafx.runtime.async.BackgroundExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.management.OperatingSystemMXBean;
import java.util.Date;
import java.util.List;
import java.util.zip.DataFormatException;

/**
 * @author 邓亚非
 */
@Service
@Slf4j
public class ResumeServiceImpl implements ResumeService {
    @Autowired
    ResumeEntityMapper resumeEntityMapper;
    @Autowired
    ResumeEntityExample resumeEntityExample;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    DeliveryEntityMapper deliveryEntityMapper;
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    HttpServletRequest request;
    @Autowired
    EnterpriseEntityMapper enterpriseEntityMapper;
    @Autowired
    GraduateEntityMapper graduateEntityMapper;

    /**
     * 查询简历信息
     *
     * @param resumeQueryByGidVO
     * @return
     */
    @Override
    public ResumeEntity queryByGid(ResumeQueryByGidVO resumeQueryByGidVO) {
        return resumeEntityMapper.queryByGid(resumeQueryByGidVO.getGid());
    }


    /**
     * 发送面试邮件
     *
     * @param sendEmailVO
     * @return
     */
    @Override
    public Boolean sendInterviewEmail(SendEmailVO sendEmailVO) throws DataFormatException {
        String time = null;
        try {
            time = DateUtil.dateTimeToString(sendEmailVO.getInterviewTime());
            System.out.println("面试时间:" + time);
        } catch (Exception e) {
            e.printStackTrace();
            new RestApiResult(e);
            log.error("日期转换异常");
        }
        String text = "面试地点:" + sendEmailVO.getInterviewLocaltion() + "-面试时间:" + time + "-面试形式:" + sendEmailVO.getInterviewForm() + ",面试链接:" + sendEmailVO.getInterviewHref() + ",面试寄语:" + sendEmailVO.getInterviewMessage() + ",联系方式:" + sendEmailVO.getInterviewLink();
        System.out.println(text);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(sendEmailVO.getInterviewTitle());
        simpleMailMessage.setFrom(RecommendConstant.SEND_ACCOUNT);
        simpleMailMessage.setTo(sendEmailVO.getInterviewQQ());
        simpleMailMessage.setSentDate(new Date());
        simpleMailMessage.setText(text);
        javaMailSender.send(simpleMailMessage);
        Integer integer = deliveryEntityMapper.updateStatus(sendEmailVO.getDid(), RecommendConstant.PROCESSING);
        if (integer.equals(RecommendConstant.OPERATION_SUCCESS)) {
            return true;
        }
        return false;
    }

    /**
     * 发送录用邮件
     *
     * @param resumeApplyVO
     * @return
     */
    @Override
    public Boolean sendApplyEmail(ResumeApplyVO resumeApplyVO) {
        String string = DateUtil.dateToString(resumeApplyVO.getTime());
        String text = "恭喜你!成功的应聘上了我司" + resumeApplyVO.getCompany() + resumeApplyVO.getPosition() + "的岗位," + "报道时间:" + string + ";" + ";联系方式:" + resumeApplyVO.getLink() + ";" + resumeApplyVO.getMessage();
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(resumeApplyVO.getTitle());
        simpleMailMessage.setFrom(RecommendConstant.SEND_ACCOUNT);
        simpleMailMessage.setTo(resumeApplyVO.getEmail());
        simpleMailMessage.setSentDate(new Date());
        simpleMailMessage.setText(text);
        javaMailSender.send(simpleMailMessage);
        Integer integer = deliveryEntityMapper.updateStatus(resumeApplyVO.getDid(), RecommendConstant.APPLY_SUCCESS);
        if (integer.equals(RecommendConstant.OPERATION_SUCCESS)) {
            return true;
        }
        return false;
    }

    /**
     * 添加一个分享
     *
     * @param shareVO
     * @return
     */
    @Override
    public Boolean addShare(ShareVO shareVO) {
        RedisShareEntity redisShareEntity = BeanHelper.copyProperties(shareVO, RedisShareEntity.class);
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        EnterpriseEntity enterpriseEntity = enterpriseEntityMapper.queryAllByHname(userInfo);

        String shareKey = String.valueOf(enterpriseEntity.getHid());
        //        查询是否出现重复的分享
        List<Object> range = redisTemplate.opsForList().range(shareKey, 0, -1);
        List<RedisShareEntity> redisShareEntities = BeanHelper.copyWithCollection(range, RedisShareEntity.class);
        if (!CollectionUtils.isEmpty(redisShareEntities)) {
            for (RedisShareEntity redisShare : redisShareEntities) {
                if (redisShare.getContent().equals(shareVO.getContent())) {
                    return false;
                }
            }
        }
        try {
            Long aLong = redisTemplate.opsForList().leftPush(shareKey, redisShareEntity);
            RedisListUtil.addShareKey(redisTemplate, shareKey);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询所有的分享
     *
     * @param
     * @return
     */
    @Override
    public List<RedisShareEntity> queryAllShare() {
//        找到对应的key
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        EnterpriseEntity enterpriseEntity = enterpriseEntityMapper.queryAllByHname(userInfo);
        String keyShare = String.valueOf(enterpriseEntity.getHid());
        List<Object> range = redisTemplate.opsForList().range(keyShare, 0, -1);
        List<RedisShareEntity> redisShareEntities = BeanHelper.copyWithCollection(range, RedisShareEntity.class);
        return redisShareEntities;
    }

    /**
     * 删除一个分享
     *
     * @param resumeDeleteShareVO
     * @return
     */
    @Override
    public Boolean deleteShare(ResumeDeleteShareVO resumeDeleteShareVO) {
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        EnterpriseEntity enterpriseEntity = enterpriseEntityMapper.queryAllByHname(userInfo);
        String key = String.valueOf(enterpriseEntity.getHid());
        List<Object> range = redisTemplate.opsForList().range(key, 0, -1);
        List<RedisShareEntity> redisShareEntities = BeanHelper.copyWithCollection(range, RedisShareEntity.class);
        long index = -1;
        RedisShareEntity redisShareEntity = null;
//        不为空再删除
        for (int i = 0; i < redisShareEntities.size(); i++) {
            if (redisShareEntities.get(i).getContent().equals(resumeDeleteShareVO.getContent())) {
                index = i;
                redisShareEntity = redisShareEntities.get(i);
            }
        }

        try {
            Long remove = redisTemplate.opsForList().remove(key, index, redisShareEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 计算简历分数
     *
     * @param gid
     * @return
     */
    @Override
    public ResumeInfoEntity computedScore(Integer gid) {
        ResumeEntity resumeEntity = resumeEntityMapper.queryByGid(gid);
        ResumeInfoEntity resumeInfoEntity = new ResumeInfoEntity();
        if (ObjectUtils.isEmpty(resumeEntity)) {
            resumeInfoEntity.setScore(RecommendConstant.ZERO);
            resumeInfoEntity.setIdentify("未知");
            return resumeInfoEntity;
        }
//        不为空
        if (resumeEntity.getEducation().equals(RecommendConstant.COMMON_EDUCATION)) {
            resumeInfoEntity.setScore(RecommendConstant.PASS_SCORE);
        } else if (resumeEntity.getEducation().equals(RecommendConstant.THE_EDUCATION)) {
            resumeInfoEntity.setScore(RecommendConstant.PASS_SCORE + 10);
        } else if (resumeEntity.getEducation().equals(RecommendConstant.NHE_EDUCATION)) {
            resumeInfoEntity.setScore(RecommendConstant.PASS_SCORE + 20);
        } else if (resumeEntity.getEducation().equals(RecommendConstant.COMMOM_MASTER)) {
            resumeInfoEntity.setScore(RecommendConstant.PASS_SCORE + 25);
        } else if (resumeEntity.getEducation().equals(RecommendConstant.THE_MASTER)) {
            resumeInfoEntity.setScore(RecommendConstant.PASS_SCORE + 30);
        } else if (resumeEntity.getEducation().equals(RecommendConstant.NHE_MASTER)) {
            resumeInfoEntity.setScore(RecommendConstant.PASS_SCORE + 35);
        }
        resumeInfoEntity.setIdentify(resumeEntity.getIdentify());
        resumeInfoEntity.setCity(resumeEntity.getCity());
        resumeInfoEntity.setEducation(resumeEntity.getEducation());
        return resumeInfoEntity;
    }

    /**
     * 查询简历信息
     *
     * @return
     */
    @Override
    public ResumeEntity queryResumeByGid() {
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(userInfo);
        return resumeEntityMapper.queryByGid(graduateEntity.getGid());
    }

    /**
     * 添加简历
     *
     * @param resumeAddVO
     * @return
     */
    @Override
    public Integer insertResume(ResumeAddVO resumeAddVO) {
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(userInfo);
        ResumeEntity resumeEntity = BeanHelper.copyProperties(resumeAddVO, ResumeEntity.class);
        resumeEntity.setGid(graduateEntity.getGid());
        return resumeEntityMapper.insertSelective(resumeEntity);
    }

    /**
     * 更新简历
     *
     * @param resumeUpdateVO
     * @return
     */
    @Override
    public Integer updateResume(ResumeUpdateVO resumeUpdateVO) {
        ResumeEntity resumeEntity = BeanHelper.copyProperties(resumeUpdateVO, ResumeEntity.class);
        return resumeEntityMapper.updateByPrimaryKeySelective(resumeEntity);
    }
}